import {_decorator,
    Component,
    Node,
    v2,
    Vec3,
    log,
    v3,
    EventTouch,
    Vec2,} from 'cc';

const {ccclass, property} = _decorator;

//
let touchDelta = v2();
let tmpV3 = v3();

@ccclass('Joystick')
export class Joystick extends Component {
    // [1]
    // dummy = '';

    // [2]
    // @property
    // serializableDummy = 0;

    @property({type: Node })
    nd_center: Node = null!;

    @property
    maxR = 120;

    // private
    offset = v2();
    initCenterPos = v3();

    start() {
        // [3]

        // move
        this.nd_center.on(Node.EventType.TOUCH_START,this.touchBegin,this);
        this.nd_center.on(Node.EventType.TOUCH_MOVE,this.touchMove,this);
        this.nd_center.on(Node.EventType.TOUCH_END,this.touchEnd,this);
        this.nd_center.on(Node.EventType.TOUCH_CANCEL,this.touchEnd,this);

        Vec3.copy(this.initCenterPos,this.nd_center.position);
    }

    touchBegin(event:EventTouch){
        log("touchBegin called!");
    }
    touchMove(event:EventTouch){
        let delta = event.getDelta(touchDelta);
        Vec3.set(tmpV3,delta.x,delta.y,0);
        let newPos = Vec3.add(tmpV3,this.nd_center.position,tmpV3);

        let distSquare = Vec3.squaredDistance(this.initCenterPos,newPos);
        if (distSquare > this.maxR * this.maxR){
            let dir = Vec3.subtract(tmpV3,newPos,this.initCenterPos);
            let normalDir = Vec3.normalize(dir,dir);
            Vec3.scaleAndAdd(tmpV3,this.initCenterPos,normalDir,this.maxR);
            this.nd_center.position = tmpV3;
        }else{
            this.nd_center.position = newPos;
        }
    }
    touchEnd(event:EventTouch){
        this.nd_center.position = this.initCenterPos;
    }

    getMoveDir(outVec3:Vec3){
        Vec3.subtract(outVec3,this.nd_center.position,this.initCenterPos);
        return outVec3;
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.0/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.0/manual/en/scripting/ccclass.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.0/manual/en/scripting/life-cycle-callbacks.html
 */
